"""
这个文件是用来批量对MySQL中的数据进行初始化使用的
"""
import os
import pymysql

# 配置数据库参数
db_config = {
    'user': 'root',
    'password': '10122024',
    'host': '127.0.0.1',
    'charset': 'utf8mb4'
}

def init_database():
    # 创建数据库连接
    conn = pymysql.connect(**db_config)
    
    try:
        # 创建游标对象
        with conn.cursor() as cursor:
            # 创建app_base数据库
            cursor.execute("CREATE DATABASE IF NOT EXISTS app_base")

            # 使用app_base数据库
            cursor.execute("USE app_base")

            # 文件夹路径
            folder_path = './database_1215'

            # 获取文件夹内所有.sql文件
            sql_files = [f for f in os.listdir(folder_path) if f.endswith('.sql')]

            # 逐个执行每个SQL文件
            for sql_file in sql_files:
                file_path = os.path.join(folder_path, sql_file)
                
                with open(file_path, 'r', encoding='utf-8') as file:
                    sql_script = file.read()
                
                # 分割并执行SQL语句
                statements = sql_script.split(';')
                for statement in statements:
                    clean_statement = statement.strip()
                    if clean_statement:
                        try:
                            cursor.execute(clean_statement)
                            print(f"Executed: {clean_statement[:50]}...")
                        except pymysql.Error as e:
                            print(f"Error executing statement: {e}")
                            print(f"Problematic statement: {clean_statement}")

            # 提交更改
            conn.commit()

    except pymysql.Error as e:
        print(f"Database error: {e}")
        conn.rollback()

    finally:
        # 关闭连接
        conn.close()

    print("All SQL files executed successfully.")

if __name__ == '__main__':
    init_database()